#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import logging
import re
import json
from utils import utils_data, ErrorInfoBuilder

logger = logging.getLogger('my_logger')


def check_testcase():
    file_entities = utils_data.get_file()
    if not file_entities:
        logger.error("未获取到文件信息")
        return

    has_error = False

    for file_entity in file_entities:
        if file_entity.file_name.endswith(('.test.ets', '.test.js')):
            file_path = file_entity.full_path
            relative_path = file_entity.file_path
            language = "arkts" if file_entity.file_name.endswith('.test.ets') else "javascript"

            testsuite_regex = re.compile(r'describe\s*\(\s*["\'](.*?)["\']\s*,')
            testcase_regex = re.compile(r'^\s*it\s*\(\s*["\'](.*?)["\']\s*,')

            testsuite_testcases = {}
            current_testsuite = "default_testsuite"

            with open(file_path, 'r', encoding='utf-8') as file:
                for line_number, line in enumerate(file, start=1):
                    line = line.strip()

                    testsuite_match = testsuite_regex.search(line)
                    testcase_match = testcase_regex.search(line)

                    if testsuite_match:
                        current_testsuite = testsuite_match.group(1)
                        if current_testsuite not in testsuite_testcases:
                            testsuite_testcases[current_testsuite] = []
                    elif testcase_match:
                        testcase = testcase_match.group(1)
                        if current_testsuite not in testsuite_testcases:
                            testsuite_testcases[current_testsuite] = []
                        if testcase in testsuite_testcases[current_testsuite]:
                            error_info = ErrorInfoBuilder() \
                                .set_buggy_file_path(relative_path) \
                                .set_defect_type("XTS.CHECK.TESTCASE.01") \
                                .set_description("测试组件testcase在同一个测试套中命名不能重复") \
                                .set_main_buggy_line(line_number) \
                                .set_main_buggy_code(line) \
                                .set_language(language) \
                                .build()

                            utils_data.write_error_to_json_file(error_info)
                            logger.info(json.dumps(error_info, indent=4, ensure_ascii=False))
                            has_error = True
                        else:
                            testsuite_testcases[current_testsuite].append(testcase)

    if has_error:
        logger.info("测试组件 testcase命名重复问题检查完成，错误信息已写入 xts_result.json")
    else:
        logger.info("测试组件 testcase命名重复问题检查通过")